package com.poi.jms;

import javax.jms.*;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

public class JmsMain {

	/**
	 * @param args
	 * @throws JMSException 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws JMSException, InterruptedException {
		  
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"failover://tcp://localhost:61616");
		Connection connection = factory.createConnection();
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		connection.start();
		Queue queue = session.createQueue("TOOL.DEFAULT");
		MessageProducer producer = session.createProducer(queue);
		int i = 0;
		// for (int i = 0; i < 100; i++) {
			TextMessage textMessage = session.createTextMessage("test message index:" + i);
			producer.setDeliveryMode(DeliveryMode.PERSISTENT);
			producer.send(textMessage);
	 	//}
		
		  connection.close();
		
		  consume();
			 
	}
	private static void consume() throws JMSException {
		ActiveMQConnectionFactory factory2 = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER,ActiveMQConnection.DEFAULT_PASSWORD,"failover://tcp://localhost:61616");
		Connection connection2 = factory2.createConnection();
		connection2.start();
		Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
		Queue queue2 = session2.createQueue("TOOL.DEFAULT");
		MessageConsumer consumer = session2.createConsumer(queue2);
		consumer.setMessageListener(new MessageListener() {
			@Override
			public void onMessage(Message arg0) {
				System.out.println(arg0);
				if (arg0 instanceof TextMessage) {
					try {
						System.out.println(((TextMessage) arg0).getText());
					} catch (JMSException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		 connection2.close();
		
	}
	
}

